﻿using log4net;
using MimeKit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ScanDispatcher
{
    public class SmtpServer
    {
        public static bool run = true;
        public static void Serve()
        {
            var logger = LogManager.GetLogger("ScanDispatcher");
            try
            {
                logger.Debug("Trying to listen on port " + ScanDispatcher.Properties.Settings.Default.Port);

                var endpoint = new IPEndPoint(IPAddress.Any, ScanDispatcher.Properties.Settings.Default.Port);

                var server = new TcpListener(endpoint);
                server.Start();

                while (run)
                {
                    TcpClient client = server.AcceptTcpClient();
                    var handler = new SmtpHandler { Stream = client.GetStream() };
                    Thread thread = new System.Threading.Thread(new ThreadStart(handler.ProcessMessage));
                    thread.Start();
                }
            }
            catch (Exception ex)
            {
                logger.Fatal("Unable to start", ex);

            }

        }
    }

}
